package com.example.cachewebview

import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.example.cachewebview.bean.WebNavigationBean
import com.example.cachewebview.bean.WebPaintBean
import com.example.cachewebview.bean.WebPerfBean
import com.example.cachewebview.bean.WebPerformanceBean
import com.example.cachewebview.util.UrlManager
import com.fan.cachewebview.R
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken

/**
 * @description $
 * @date: 2022/5/10 13:52
 * @author: fan
 */
class NormalWebActivity : AppCompatActivity() {
    private lateinit var webView: WebView
    private lateinit var imgViewCache: ImageView

    private var targetUrl: String = ""
    private lateinit var flGroup: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web)
        targetUrl = intent.getStringExtra("url").toString()
        initView()
        initWebSettings()
        initWebCacheAndLoad()
    }

    private fun initView() {
        flGroup = findViewById(R.id.fl)
        webView = WebView(this)
        val params = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        flGroup.addView(webView, params)
    }

    private fun initWebSettings() {
        // 基础配置
        val webSettings: WebSettings = webView.settings
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.javaScriptEnabled = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.useWideViewPort = true
        webSettings.domStorageEnabled = true
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webView.addJavascriptInterface(this, "web")
    }


    private fun initWebCacheAndLoad() {
        webView.webViewClient = mWebViewClient
        webView.loadUrl(targetUrl)
    }


    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            view.evaluateJavascript(
                UrlManager.JS_MONITOR,
                null
            )
        }

        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            // 接受所有网站的证书
            handler.proceed()
        }
    }

    override fun onBackPressed() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack()
        } else {
            finish()
        }
    }
    // 性能监控
    @JavascriptInterface
    fun setH5Performance(timing: String?, curUrl: String?, paint: String?, navigation: String?) {
        try {
            val bean: WebPerformanceBean = Gson().fromJson(timing, WebPerformanceBean::class.java)
            var event = WebPerfBean()
            // paint 处理
            if (!TextUtils.isEmpty(paint)) {
                var webFpFcpBeans: List<WebPaintBean>? = null
                try {
                    val userListType = object : TypeToken<List<WebPaintBean?>?>() {}.type
                    webFpFcpBeans = Gson().fromJson<List<WebPaintBean>>(paint, userListType)
                } catch (e: JsonSyntaxException) {
                    e.printStackTrace()
                }

                if (webFpFcpBeans != null && webFpFcpBeans.size > 1) {
                    event.fp = (webFpFcpBeans[0].startTime).toLong()
                    event.fcp = webFpFcpBeans[0].startTime.toLong()

                    if (event.fp < 0) {
                        event.fp = bean.domInteractive - bean.navigationStart
                    }
                    if (event.fcp < 0) {
                        event.fcp = bean.loadEventEnd - bean.navigationStart
                    }

                } else {
                    event.fp = bean.domInteractive - bean.navigationStart
                    event.fcp = bean.loadEventEnd - bean.navigationStart
                }

            } else {
                event.fp = bean.domInteractive - bean.navigationStart
                event.fcp = bean.loadEventEnd - bean.navigationStart
            }
            // navigation 处理
            if (!TextUtils.isEmpty(navigation)) {
                var webNavigationBeans: List<WebNavigationBean>? = null
                try {
                    val userListType = object : TypeToken<List<WebNavigationBean?>?>() {}.type
                    webNavigationBeans =
                        Gson().fromJson<List<WebNavigationBean>>(navigation, userListType)
                } catch (e: JsonSyntaxException) {
                    e.printStackTrace()
                }
                if (webNavigationBeans != null && webNavigationBeans.isNotEmpty()) {
                    event.du = webNavigationBeans[0].duration.toLong()
                } else {
                    event.du = bean.loadEventEnd - bean.navigationStart
                }
            } else {
                event.du = bean.loadEventEnd - bean.navigationStart
            }

            Log.d("fanLoad", event.toString())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        if (flGroup != null) {
            flGroup.removeView(webView)
        }
        if (webView != null){
            webView.clearHistory()
            webView.settings.javaScriptEnabled = false
            webView.settings.blockNetworkImage = false
            webView.clearCache(true)
            webView.destroy()
        }
        super.onDestroy()
    }


}